package top.zerozoo.learn.grade.servlet;

import org.apache.commons.beanutils.BeanUtils;
import top.zerozoo.learn.grade.entity.Admin;
import top.zerozoo.learn.grade.factory.ServiceFactory;
import top.zerozoo.learn.grade.service.AdminService;
import top.zerozoo.learn.grade.vo.AdminInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
//        判断是否已登录
        if(session.getAttribute("adminInfo")!=null){
            resp.sendRedirect(req.getContextPath()+"/admin.do");
            return;
        }

        Map<String, String[]> parameterMap = req.getParameterMap();
//        如果未提供参数 则直接转发到login.jsp
        if (parameterMap.size() <= 0) {
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            return;
        }

        Admin admin = new Admin();
        try {
            BeanUtils.populate(admin, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        AdminInfo adminInfo;
        if((adminInfo = ServiceFactory.get(AdminService.class).login(admin)) == null){
            req.setAttribute("error_msg", "用户名或密码不正确！");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }else{
            session.setAttribute("adminInfo",adminInfo);
            resp.sendRedirect(req.getContextPath()+"/admin.do");
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
